package com.android.utils;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

public abstract class DateUtils
{
	public static final String DATE_FORMAT_EEEE_DD_MMMM = "EEEE, dd MMMM";
	public static final String DATE_FORMAT_DEFAULT = "dd-MM-yyyy";
	public static final String DATE_FORMAT_PT_BR = "dd/MM/yyyy";
	
	public static String getFormatedDate(String format)
	{
		SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault()); 
		return dateFormat.format(new Date());
	}
	
	public static String getFormatedDate(String format, Date date)
	{
		SimpleDateFormat dateFormat = new SimpleDateFormat(format, Locale.getDefault()); 
		return dateFormat.format(date);
	}
	
	public static String getFormatedDate(String format, int day, int month, int year)
	{
		Calendar calendar = Calendar.getInstance();
		return getFormatedDate(format, calendar.getTime());
	}
	
	public static Date getFirstDayOfCurrentWeek()
	{
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_WEEK, cal.getFirstDayOfWeek());
		
		return cal.getTime();
	}
	
	public static Date plusDayOnDate(Date date, int days)
	{
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		c.add(Calendar.DATE, days);
		return c.getTime();
	}
	
	public static boolean isDateBetween(Date initialDate, Date finalDate, Date dateBetween)
	{
		return dateBetween.compareTo(initialDate) >= 0 && dateBetween.compareTo(finalDate) <= 0;
	}
	
	/**
	 * @author Kleber Damasco
	 * @param list
	 * @param date
	 * @param field_
	 * @return
	 */
	public static <T> List<T> filterByDate(List<T> list, Date date, String field_) {
		List<T> aux = new ArrayList<T>(0);
		Iterator<T> iterator = list.iterator();

		while(iterator.hasNext()) {
			T next = iterator.next();
			try {
				Field field = next.getClass().getField(field_);
				field.setAccessible(true);
				Date date1 = (Date) field.get(next);

				date = clearTime(date);
				date1 = clearTime(date1);
				if(date.equals(date1)) {
					aux.add(next);
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return aux;
	}

	private static Date clearTime(Date object) {
		Calendar c = Calendar.getInstance();
		c.setTime(object);
		c.clear(Calendar.HOUR);
		c.clear(Calendar.MINUTE);
		c.clear(Calendar.SECOND);
		c.clear(Calendar.MILLISECOND);
		return c.getTime();
	}
	
}
